<script lang="ts">
    import dayjs from "dayjs";
    import { useDatepickerContext } from "./Datepicker.svelte";
    import DatePane from "./DatePane.svelte";
    import TimePane from "../Timepicker/TimePane.svelte";
    import Icon from "../Common/Icons/Icon.svelte";
    import { _ } from "svelte-i18n";

    const props = $props();
    let tab = $state("date");
    const ctx: any = useDatepickerContext();
    const val = $derived(props.store.currentMonth[props.name === "end" ? 1 : 0]);

    // const val = () => props.value || new Date();

    const displayDate = () => {
        return dayjs(props.value || new Date()).format("YYYY-MM-DD");
    };
    const displayTime = () => {
        return dayjs(val).format("HH:mm:ss");
    };

    const selectTab = (atab: string) => {
        tab = atab;
    };

    const onSelectTime = (type: string, num: number, name: string) => {
        const v = new Date(val);

        if (type === "hour") {
            v.setHours(num);
        }
        if (type === "minute") {
            v.setMinutes(num);
        }
        if (type === "second") {
            v.setSeconds(num);
        }
        ctx && ctx.onSelectTime(v, props.name);
    };
</script>

<div class="cm-date-picker-datetime">
    <div class="cm-datetime-content">
        {#if tab === "date"}
            <DatePane {...props} />
        {/if}
        {#if tab === "time"}
            <TimePane {...props} header={$_("Timepicker.header")} value={dayjs(val)} {onSelectTime} />
        {/if}
    </div>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="cm-datetime-switch">
        <!-- svelte-ignore a11y_click_events_have_key_events -->
        <div class={{ "cm-datetime-switch-item": true, active: tab === "date" }} onclick={selectTab.bind(null, "date")}>
            <Icon icon="calendar" size={props.compact ? 12 : 16} />
            {displayDate()}
        </div>
        <!-- svelte-ignore a11y_click_events_have_key_events -->
        <div class={{ "cm-datetime-switch-item": true, active: tab === "time" }} onclick={selectTab.bind(null, "time")}>
            <Icon icon="clock" size={props.compact ? 12 : 16} />
            {displayTime()}
        </div>
    </div>
</div>
